import { saveToStorage, getFromStorage } from "../storage.js";

const HOLIDAYS_KEY = "holidays";
const HOLIDAYS_TTL_MS = 1000 * 60 * 60 * 24 * 7; // 1 week

export async function fetchHolidays(countryCode) {
  const year = new Date().getFullYear();
  const url = `https://date.nager.at/api/v3/PublicHolidays/${year}/${countryCode}`;
  const res = await fetch(url);
  if (!res.ok) throw new Error("Failed to fetch holidays");
  const data = await res.json();
  const payload = { countryCode, year, list: data, ts: Date.now() };
  await saveToStorage(`${HOLIDAYS_KEY}_${countryCode}`, payload);
  return payload;
}

export async function getHolidays(countryCode) {
  const cached = await getFromStorage(`${HOLIDAYS_KEY}_${countryCode}`);
  if (cached && Date.now() - (cached.ts || 0) < HOLIDAYS_TTL_MS) return cached;
  return fetchHolidays(countryCode);
}

export async function scheduleHolidayRefresh(force = false) {
  const country = (await getFromStorage("settings"))?.country || "US";
  const cached = await getFromStorage(`${HOLIDAYS_KEY}_${country}`);
  if (force || !cached || Date.now() - (cached.ts || 0) >= HOLIDAYS_TTL_MS) {
    try {
      await fetchHolidays(country);
    } catch (_e) {}
  }
}
